<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.nickname" clearable class="filter-item" style="width: 160px;" placeholder="请输入客户名称" />
      <el-input v-model="listQuery.orderSn" clearable class="filter-item" style="width: 160px;" placeholder="请输入订单编号" />
      <el-date-picker v-model="listQuery.timeArray" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" class="filter-item" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" />
      <el-select v-model="listQuery.orderStatusArray" multiple style="width: 200px" class="filter-item" placeholder="请选择订单状态">
        <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value" />
      </el-select>
      <el-select v-model="listQuery.orderType" @change="changeType" placeholder="请选择订单类型">
        <el-option
          v-for="item in categoryList"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>

      <el-button v-permission="['GET /admin/order/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <!-- <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button> -->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column type="expand">
        <template slot-scope="props">
          <div class="orders">
            <div class="name">
              项目名称：{{ props.row.projectName }}
            </div>
            <div class="spec">
              公里数：{{ props.row.kilonumber }}km
            </div>
            <div class="num">
              收货地址：{{ props.row.address }}
            </div>
            <div class="price">
              租用天数：{{ props.row.zuDay }} 天
            </div>
            <div class="price">
              运费：{{ props.row.freightPrice }} 元
            </div>
            <div class="price">
              租金费用：{{ props.row.goodsPrice }} 元
            </div>
            <div class="price">
              订单总金额：{{ props.row.orderPrice }} 元
            </div>
           <div class="price">
             押金：{{ props.row.yajinPrice }} 元
           </div>
            <div class="price">
              备注：{{ props.row.remarks }}
            </div>


          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="120" label="订单编号" prop="orderSn" />

      <el-table-column align="center" label="用户头像" width="80">
        <template slot-scope="scope">
          <el-avatar :src="scope.row.avatar" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="下单时间" prop="addTime" min-width="100">
        <template slot-scope="scope">
          {{ (scope.row.addTime || '').substring(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="订单状态" prop="orderStatus">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.orderStatus | orderStatusFilter }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="订单金额" prop="orderPrice">
        <template slot-scope="scope">
          {{ scope.row.orderPrice }} 元
        </template>
      </el-table-column>

      <el-table-column align="center" label="实付金额" prop="actualPrice">
        <template slot-scope="scope">
          {{ scope.row.actualPrice }} 元
        </template>
      </el-table-column>

      <el-table-column align="center" label="开始时间" prop="startTime" />
      <el-table-column align="center" label="结束时间" prop="overTime" />

      <el-table-column align="center" label="收货人" prop="consignee">
        <template slot-scope="scope">
          <span style="color:red; font-weight:bold;">{{ scope.row.consignee }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="收货电话" prop="mobile" min-width="100" />
      <el-table-column align="center" label="操作" width="250" class-name="oper">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleDetail(scope.row)">详情</el-button>
          <el-button v-if="scope.row.orderStatus == 101" type="info" size="mini" @click="handleQx(scope.row)">取消订单</el-button>
          <el-button v-if="scope.row.orderStatus == 101" type="danger" size="mini" @click="handleQr(scope.row)">确认订单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />


    <!-- 订单详情对话框 -->
    <el-dialog :visible.sync="orderDialogVisible" title="订单详情" width="800px">
      <section ref="print">
        <el-form :data="orderDetail" label-position="left">
          <el-form-item label="订单编号">
            <span>{{ orderDetail.order.orderSn }}  <el-tag>{{ orderDetail.order.orderStatus | orderStatusFilter }}</el-tag></span>
          </el-form-item>
          <div class="popdetail">
            <div class="name">
               项目名称：{{ orderDetail.order.projectName }}
             </div>
             <div class="spec">
               公里数：{{ orderDetail.order.kilonumber }}km
             </div>
             <div class="price">
               租用天数：{{ orderDetail.order.zuDay }} 天
             </div>
             <div class="price">
               运费：{{ orderDetail.order.freightPrice }} 元
             </div>
             <div class="price">
               租金费用：{{ orderDetail.order.goodsPrice }} 元
             </div>
             <div class="price">
               订单总金额：{{ orderDetail.order.orderPrice }} 元
             </div>
            <div class="price">
              押金：{{ orderDetail.order.yajinPrice }} 元
            </div>
             <div class="price">
               备注：{{ orderDetail.order.remarks }}
             </div>
          </div>
          <el-form-item label="收货信息">
            <span>（收货人）{{ orderDetail.order.consignee }}</span>
            <span>（手机号）{{ orderDetail.order.mobile }}</span>
            <span>（地址）{{ orderDetail.order.address }}</span>
          </el-form-item>
          <el-form-item label="商品信息">
            <el-table :data="orderDetail.orderGoods" border fit highlight-current-row>
              <el-table-column align="center" label="商品名称" prop="goodsName" />
              <el-table-column align="center" label="商品编号" prop="goodsSn" />
              <el-table-column align="center" label="每日/元" prop="dayPrice" />
              <el-table-column align="center" label="每月/元" prop="monthPrice" />
              <el-table-column align="center" label="商品总价" prop="goodsPrice" />
              <el-table-column align="center" label="货品数量" prop="number" />
              <el-table-column align="center" label="货品图片" prop="picUrl">
                <template slot-scope="scope">
                  <img :src="scope.row.picUrl" width="40">
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="费用信息">
            <span>
              (实际费用){{ orderDetail.order.actualPrice }}元 =
              (商品总价){{ orderDetail.order.goodsPrice }}元 +
              (运费){{ orderDetail.order.freightPrice }}元 -
              (押金){{ orderDetail.order.yajinPrice }}元[可退]
            </span>
          </el-form-item>
          <el-form-item label="支付信息">
            <span>（支付渠道）微信支付</span>
            <span>（支付时间）{{ orderDetail.order.payTime }}</span>
          </el-form-item>
          <el-form-item label="收货信息">
            <span>（确认收货时间）{{ orderDetail.order.confirmTime }}</span>
          </el-form-item>
          <el-form-item label="手动确认收款" v-if="orderDetail.order.orderStatus==104">
            <span>
              <el-input style="width: 320px;" v-model="refundContent" placeholder="手动收款原因"></el-input>
              <el-button type="success" @click="clickQd(orderDetail.order.id)">确认</el-button>
            </span>
          </el-form-item>

          <el-form-item label="其他信息" v-if="orderInfos">
            <span class="others">
              <el-row :gutter="20">
                <el-col :span="7" v-if="orderInfos.sign_url">
                  <h4>签约合同</h4>
                  <p>签约用户：{{ orderDetail.order.userId }}  、 {{ orderDetail.user.nickname }}</p>
                  <a :href="orderInfos.sign_url" target="_blank">点击查看</a>
                </el-col>
                <el-col :span="7" v-if="orderInfos.jcd_url">
                  <h4>进场单</h4>
                  <p>签约用户：{{ orderDetail.order.userId }} 、 {{ orderDetail.user.nickname }}</p>
                  <a :href="orderInfos.jcd_url" target="_blank">点击查看</a>
                </el-col>
                <el-col :span="7" v-if="orderInfos.lcd_url">
                  <h4>离场单</h4>
                  <p>签约用户：{{ orderDetail.order.userId }} 、 {{ orderDetail.user.nickname }}</p>
                  <a :href="orderInfos.lcd_url" target="_blank">点击查看</a>
                  <p>
                    索赔理由：{{ orderDetail.order.suopei }}
                  </p>
                </el-col>
              </el-row>
            </span>
          </el-form-item>
        </el-form>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="printOrder">打 印</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.popdetail{
  overflow: hidden;
  div{
    width: 50%;
    float: left;
    line-height: 25px;
  }
}
.el-table--medium th, .el-table--medium td {
    padding: 3px 0;
}

.el-input-number--medium {
  width: 100%;
}

.oper .el-button--mini {
  padding: 7px 4px;
  width: 60px;
  font-size: 10px;
  margin-left: 1px;
}

::v-deep .el-table__expanded-cell {
  padding: 6px 80px;
}

.order-goods {
  display: flex;
  justify-content: space-around;
  justify-items: center;
  align-items:center;
  padding: 6px 0;
}

.name {
  width: 400px;
}

.spec {
  width: 180px;
}

.price {
  // width: 120px;
}

.num {
  width: 120px;
}
.orders div{
  line-height: 30px;
}
.others h4{
  margin: 0;
}
.others p{
  margin: 0;
  padding: 0;
}
.others a{
  color: blue;
  text-decoration: underline;
}
</style>

<script>
import { detailOrder, listOrder, orderChannel, orderSour, payOrder, deleteOrder, shipOrder, orderPdfurl, orderSk } from '@/api/order'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import checkPermission from '@/utils/permission' // 权限判断函数

const statusMap = {
  101: '确认中',
  102: '已确认',
  103: '取消',
  104: '订单签约成功',
  201: '支付完成',
  202: '已生成进场单',
  301: '已进场',
  401: '订单结束'
}

export default {
  name: 'Order',
  components: { Pagination },
  filters: {
    orderStatusFilter(status) {
      return statusMap[status]
    }
  },
  data() {
    return {
      inputsk: '',
      list: [],
      total: 0,
      listLoading: true,
      categoryList: [{
        label: '商城订单',
        value: '0'
      },{
        label: '员工订单',
        value: '1'
      }],
      listQuery: {
        page: 1,
        limit: 20,
        nickname: undefined,
        consignee: undefined,
        orderSn: undefined,
        timeArray: [],
        orderStatusArray: [],
        sort: 'add_time',
        order: 'desc',
        orderType: '0'
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      statusMap,
      orderDialogVisible: false,
      orderDetail: {
        order: {},
        user: {},
        orderGoods: []
      },
      shipForm: {
        orderId: undefined,
        shipChannel: undefined,
        shipSn: undefined
      },
      shipDialogVisible: false,
      payForm: {
        orderId: undefined,
        orderSn: '',
        oldMoney: 0,
        newMoney: 0,
        goodsList: []
      },
      payDialogVisible: false,
      refundForm: {
        orderId: undefined,
        refundMoney: undefined
      },
      refundDialogVisible: false,
      downloadLoading: false,
      channels: [],
      orderInfos: '',
      refundContent: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    clickQd(id) {
      if(!this.refundContent){
        return
      }
      orderSk({
        orderid: id,
        refundContent:this.refundContent,
      }).then(res=>{
        this.$notify.success({
          title: '提示',
          message: '成功'
        })
        this.handleFilter()
      })
    },
    handleQx(row) {
      this.$confirm('是否取消订单？')
        .then(_ => {
          orderChannel({orderId: row.id }).then(res=>{
             this.$notify.success({
               title: '成功',
               message: '取消订单成功'
             })
             this.handleFilter()
          }).catch(err=>{
            console.log(err.data.errmsg)
            this.$notify.warning({
              title: '提示',
              message: err.data.errmsg
            })
          })
        })
        .catch(_ => {})
    },
    handleQr(row) {
      this.$confirm('是否确认订单？')
        .then(_ => {
          orderSour({orderId: row.id }).then(res=>{
            this.$notify.success({
              title: '成功',
              message: '确认订单成功'
            })
            this.handleFilter()
          })
        })
        .catch(_ => {})
    },
    changeType() {
      this.handleFilter();
    },
    checkPermission,
    getList() {
      this.listLoading = true
      if (this.listQuery.timeArray && this.listQuery.timeArray.length === 2) {
        this.listQuery.start = this.listQuery.timeArray[0]
        this.listQuery.end = this.listQuery.timeArray[1]
      } else {
        this.listQuery.start = null
        this.listQuery.end = null
      }
      if (this.listQuery.orderId) {
        detailOrder(this.listQuery.orderId).then(response => {
          this.list = []
          if (response.data.data.order) {
            this.list.push(response.data.data.order)
            this.total = 1
            this.listLoading = false
          }
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      } else {
        listOrder(this.listQuery).then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDetail(row) {
      detailOrder(row.id).then(response => {
        this.orderDetail = response.data.data
      })
      orderPdfurl({orderid: row.id}).then(res=>{
        this.orderInfos = res.data.data;
        console.log(this.orderInfos)
      })
      this.orderDialogVisible = true
    },
    handlePay(row) {
      this.payForm.orderId = row.id
      this.payForm.orderSn = row.orderSn
      this.payForm.oldMoney = row.actualPrice
      this.payForm.newMoney = row.actualPrice
      this.payForm.goodsList = row.goodsVoList
      this.payForm.goodsList.forEach(element => {
        element.onumber = element.number
      })
      this.payDialogVisible = true
    },
    confirmPay() {
      if (this.payForm.oldMoney !== this.payForm.newMoney) {
        const diff = this.payForm.newMoney - this.payForm.oldMoney
        this.$confirm('差额 ' + diff + '元， 是否确认提交')
          .then(_ => {
            this.confirmPay2()
          })
          .catch(_ => {})
      } else {
        this.confirmPay2()
      }
    },
    confirmPay2() {
      payOrder(this.payForm).then(response => {
        this.$notify.success({
          title: '成功',
          message: '订单收款操作成功'
        })
        this.getList()
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      }).finally(() => {
        this.payDialogVisible = false
      })
    },
    handleShip(row) {
      this.shipForm.orderId = row.id
      this.shipForm.shipChannel = row.shipChannel
      this.shipForm.shipSn = row.shipSn

      this.shipDialogVisible = true
      this.$nextTick(() => {
        this.$refs['shipForm'].clearValidate()
      })
    },
    confirmShip() {
      this.$refs['shipForm'].validate((valid) => {
        if (valid) {
          shipOrder(this.shipForm).then(response => {
            this.shipDialogVisible = false
            this.$notify.success({
              title: '成功',
              message: '确认发货成功'
            })
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    handleDelete(row) {
      deleteOrder({ orderId: row.id }).then(response => {
        this.$notify.success({
          title: '成功',
          message: '订单删除成功'
        })
        this.getList()
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
    },
    handleRefund(row) {
      this.refundForm.orderId = row.id
      this.refundForm.refundMoney = row.actualPrice

      this.refundDialogVisible = true
      this.$nextTick(() => {
        this.$refs['refundForm'].clearValidate()
      })
    },
    confirmRefund() {
      this.$refs['refundForm'].validate((valid) => {
        if (valid) {
          refundOrder(this.refundForm).then(response => {
            this.refundDialogVisible = false
            this.$notify.success({
              title: '成功',
              message: '确认退款成功'
            })
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['订单ID', '订单编号', '用户ID', '订单状态', '是否删除', '收货人', '收货联系电话', '收货地址']
        const filterVal = ['id', 'orderSn', 'userId', 'orderStatus', 'isDelete', 'consignee', 'mobile', 'address']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '订单信息')
        this.downloadLoading = false
      })
    },
    printOrder() {
      this.$print(this.$refs.print)
      this.orderDialogVisible = false
    }
  }
}
</script>
